//
//  HeadERPWebViewController.m
//  MIS Cloud
//
//  Created by goldeney on 14-1-22.
//  Copyright (c) 2014年 goldeneye. All rights reserved.
//

#import "AbstractCSWindowViewController.h"
#import "AnalysisURLCiphertext.h"
#import "TSActionSheet.h"
#import "DownloadViewController.h"
#import "DownLoadHandle.h"
#import "UploadViewController.h"
#import "FileUploadModel.h"
#import "ThreeDataViewController.h"
#import "GEUIAlertView.h"

@interface AbstractCSWindowViewController ()

@property (nonatomic, strong) BS_CSWbeView *basicWebView;
@property (nonatomic, strong) NSDictionary *webViewDic;
@property (nonatomic, strong) NSString *enterString;

@end

@implementation AbstractCSWindowViewController
@synthesize basicWebView = _basicWebView;
@synthesize webViewDic = _webViewDic;
@synthesize enterString = _enterString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithOpenJsonDictionary:(NSDictionary*)mDictionary enterData:(NSString*)enterStr
{
    self.webViewDic = mDictionary;
    self.enterString = enterStr;
    return [super init];
}

- (id)initWithOpenURLString:(NSString*)URLString
{
    //解析数据后得到数据结果
    NSDictionary *webViewDic = [AnalysisURLCiphertext analysisURLString:URLString];
    self.webViewDic = webViewDic;
    return [super init];
}

- (void)dealloc
{
    _basicWebView = nil;
    _webViewDic = nil;
    _enterString = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //判断是否需要标题栏
    CGRect webViewFrame = self.view.frame;
    
    NSString *htmlURL = [_webViewDic objectForKey:CSMonitorNodeDataKeyURL];
    NSString *titleName = [_webViewDic objectForKey:CSMonitorNodeDataKeyTitle];
    NSDictionary *postParas = [_webViewDic objectForKey:CSMonitorNodeDataKeyParas];
    NSDictionary *returnDatas = [_webViewDic objectForKey:CSMonitorNodeDataKeyReturn];
    
    NSDictionary *enterData = [_webViewDic objectForKey:CSMonitorNodeDataKeyEnter];
    NSString *functionBData = [enterData objectForKey:CSMonitorNodeOrderEnterFunctionB];
    
    //初始化网页控件
    _basicWebView = [[BS_CSWbeView alloc] initWithFrame:webViewFrame];
    [_basicWebView setEnterFunction:functionBData parameter:_enterString];
    _basicWebView.delegate = self;
    [self.view addSubview:_basicWebView];
    
    NSString *backName = [returnDatas objectForKey:CSMonitorNodeOrderReturnTitle];
    if (!(backName && ![backName isEqualToString:@""]))
        backName = @"返回";
    [self.navigationItem.backBarButtonItem setTitle:backName];
    
    if (!(titleName && ![titleName isEqualToString:@""]))
        titleName = @"无标题";
    self.title = titleName;
    
    [_basicWebView loadRequestURLString:htmlURL parasData:postParas];
    
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultData:(id)dataValue object:(id)object
{
    NSString *functionBData = dataValue;
    NSDictionary *returnData = object;
    NSString *functionAData = [returnData objectForKey:CSMonitorNodeOrderReturnFunctionA];
    
    //判断functionB数据是否存在
    if (functionAData && ![functionAData isEqualToString:@""]) {
        NSString *functionA = nil;
        if (functionBData && ![functionBData isEqualToString:@""]){
            functionA = [NSString stringWithFormat:@"%@(\"%@\");",functionAData,functionBData];
        } else {
            functionA = [NSString stringWithFormat:@"%@();",functionAData];
        }
        
        [_basicWebView stringByEvaluatingJavaScriptFromString:functionA];
    }
}

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    if ([key isEqualToString:@"UploadFile"]) {//上传文件返回数据
        NSMutableArray *dataArray = backValue;
        for (FileUploadModel *model in dataArray) {
            NSString *functionA = [NSString stringWithFormat:@"%@('%@');",model.functionA,model.uploadResult];
            [_basicWebView stringByEvaluatingJavaScriptFromString:functionA];
        }
    } else if([key isEqualToString:@"TreeMenu"]){//对象选择
        NSMutableArray *resultArray = backValue;
        NSString *valueInfo = [resultArray objectAtIndex:0];
        NSString *newTreeData = [resultArray objectAtIndex:1];
        NSString *functionA = [resultArray objectAtIndex:2];
        
        NSString *function = [NSString stringWithFormat:@"%@('%@','%@');",functionA,newTreeData,valueInfo];
        [_basicWebView stringByEvaluatingJavaScriptFromString:function];
    }
}

#pragma mark -
#pragma mark CSMonitorNodeOrderDelegate

- (void)returnViewControllerData:(NSDictionary*)mDictionary
{
    //获取到返回按钮数据
    NSDictionary *returnData = [mDictionary objectForKey:CSMonitorNodeDataKeyReturn];
    NSString *alertStr = [returnData objectForKey:CSMonitorNodeOrderReturnAlertStr];
    
    //弹窗处理
    if (alertStr && ![alertStr isEqualToString:@""]) {
        GEUIAlertView* dialogue = [[GEUIAlertView alloc]initWithTitle:@"温馨提示" message:alertStr
                              delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        dialogue.object = returnData;
        [dialogue show];
    } else {
        [self returnViewControllerFunction:returnData];
    }
}

- (void)returnViewControllerFunction:(NSDictionary*)returnData
{
    NSString *functionBData = [returnData objectForKey:CSMonitorNodeOrderReturnFunctionB];
    NSUInteger destroyNumbers = [[returnData objectForKey:CSMonitorNodeOrderReturnDestroyNumbers] integerValue];
    
    //关闭多个页面,不执行返回传递数据
    if (destroyNumbers>1) {
        NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        NSInteger index = viewControllers.count - destroyNumbers;//只允许返回到menu页面
        UIViewController *viewController = nil;
        
        if (index - 2 <= 0) viewController = [viewControllers objectAtIndex:1];
        else viewController = [viewControllers objectAtIndex:index];
        [self.navigationController popToViewController:viewController animated:YES];
        
    } else if (functionBData && ![functionBData isEqualToString:@""]) {
        //判断functionB数据是否存在
        NSString *functionB = [NSString stringWithFormat:@"%@();",functionBData];
        NSString *scriptString = [_basicWebView stringByEvaluatingJavaScriptFromString:functionB];
        
        //返回参数方法判定
        if (self.backResultDelagate && [self.backResultDelagate respondsToSelector:@selector(backResultData: object:)]) {
            [self.backResultDelagate backResultData:scriptString object:returnData];
        }
    }
}

- (void)downViewControllerFileName:(NSString*)fileName filePath:(NSString*)filePath
{
    //创建连接，预览文件
    DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
    [downLoad startDownExternalFile:filePath fileName:fileName];
    
    MainAppDelegate *application = [[UIApplication sharedApplication] delegate];
    DownloadViewController *abstractView = [[DownloadViewController alloc] init];
    [application.navigationController pushViewController:abstractView animated:YES];
}

- (void)upViewControllerData:(NSDictionary*)mDictionary
{
    NSString *numberType = [mDictionary objectForKey:CSMonitorNodeOrderUploadNumberType];
    NSString *extension = [mDictionary objectForKey:CSMonitorNodeOrderUploadExtension];
    NSString *functionA = [mDictionary objectForKey:CSMonitorNodeOrderUploadFunctionA];
    
    MainAppDelegate *application = [[UIApplication sharedApplication] delegate];
    UploadViewController *abstractView = [[UploadViewController alloc] init];
    [abstractView setNumberType:numberType extension:extension function:functionA];
    
    abstractView.key = @"UploadFile";
    abstractView.backResultDelagate = self;
    [application.navigationController pushViewController:abstractView animated:YES];
}

- (void)treeMenuViewControllerData:(NSDictionary*)mDictionary
{
    MainAppDelegate *application = [[UIApplication sharedApplication] delegate];
    ThreeDataViewController *abstractView = [[ThreeDataViewController alloc] init];
    [abstractView setWebViewTransmitData:mDictionary];
    
    abstractView.key = @"TreeMenu";
    abstractView.backResultDelagate = self;
    [application.navigationController pushViewController:abstractView animated:YES];
}


#pragma mark-
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //返回提示框处理
    if ([alertView isKindOfClass:[GEUIAlertView class]]) {
        GEUIAlertView *mAlertView = (GEUIAlertView*)alertView;
        NSDictionary *returnData = mAlertView.object;
        [self returnViewControllerFunction:returnData];
    }
}

#pragma mark-
#pragma mark UIButton Event

- (void)backButtonEvent:(id)sender
{
    //执行返回方法
    [self returnViewControllerData:_webViewDic];
    [super backButtonEvent:sender];
}

- (void)rightButtonEvent:(id)sender forEvent:(UIEvent*)event
{
    TSActionSheet *actionSheet = [[TSActionSheet alloc] initWithTitle:@"龙兴赛华站"];
    [actionSheet destructiveButtonWithTitle:@"刷新" block:^{
        [_basicWebView reload];
    }];
    [actionSheet addButtonWithTitle:@"站点变更" block:^{
        NSLog(@"pushed hoge1 button");
    }];
    [actionSheet addButtonWithTitle:@"报表分析" block:^{
        NSLog(@"pushed hoge2 button");
    }];
    [actionSheet addButtonWithTitle:@"历史报表" block:^{
        NSLog(@"pushed hoge3 button");
    }];
    //[actionSheet cancelButtonWithTitle:@"Cancel" block:nil];
    actionSheet.cornerRadius = 5;
    
    [actionSheet showWithTouch:event];
}

@end
